﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using SQLHelper;

namespace BBS
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load (object sender, EventArgs e)
        {
            if ( !IsPostBack )
            {
                if ( Request.QueryString["searchField"] == null )
                    this.GridViewDataBindDefault();
                else
                {
                    this.GridViewDataBindWithSearchField(Request.QueryString["searchField"].ToString());
                }
            }
        }

        private void GridViewDataBindDefault ()
        {
            //获取帖子，以发布日期从最近到最远排序
            string queryAllThemesStr = string.Format("SELECT THEME_ID,TITLE,PUBLISH_DATE,PICKNAME FROM THEME,ACCOUNT WHERE THEME.ACCOUNT_ID=ACCOUNT.ACCOUNT_ID ORDER BY PUBLISH_DATE DESC;");
            this.TryQuery(queryAllThemesStr);
        }

        private void GridViewDataBindWithSearchField (string searchField)
        {
            if ( string.IsNullOrEmpty(searchField) )
            {
                this.GridViewDataBindDefault();
                return;
            }

            string queryStr = string.Format("SELECT THEME_ID,TITLE,PUBLISH_DATE,PICKNAME FROM THEME,ACCOUNT WHERE THEME.ACCOUNT_ID=ACCOUNT.ACCOUNT_ID AND THEME.TITLE LIKE '%{0}%' ORDER BY PUBLISH_DATE DESC;", searchField);
            this.TryQuery(queryStr);
        }

        private void TryQuery (string sqlStr)
        {
            SQLHelperSingleton.TryQueryByDataSet(sqlStr, this.DataBind, null);
        }

        private void DataBind (DataSet ds)
        {
            this.gvThemes.DataSource = ds.Tables[0];
            this.gvThemes.DataBind();
        }

        protected void gvThemes_PageIndexChanging (object sender, GridViewPageEventArgs e)
        {
            this.gvThemes.PageIndex = e.NewPageIndex;
            this.GridViewDataBindDefault();
        }


    }
}